import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.io.IOException;

public class Client {
    public static void main(String[] args) throws IOException {
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("localhost", 8080));
        socketChannel.configureBlocking(false);

        // 发送请求
        ByteBuffer requestBuffer = ByteBuffer.wrap("Hello, Server!".getBytes());
        socketChannel.write(requestBuffer);

        // 清空缓冲区
        requestBuffer.clear();

        // 读取响应
        ByteBuffer responseBuffer = ByteBuffer.allocate(1024);
        StringBuilder response = new StringBuilder();

        while (true) {
            int bytesRead = socketChannel.read(responseBuffer);
                    System.out.println("Received: " + response.toString());

            if (bytesRead == 0) {
                // 没有数据可读，继续等待
                continue;
                // break;
            }
            if (bytesRead == -1) {
                // 客户端关闭连接
                break;
            } else if (bytesRead > 0) {
                responseBuffer.flip();
                byte[] data = new byte[responseBuffer.remaining()];
                responseBuffer.get(data);
                response.append(new String(data));
                responseBuffer.clear();
                break;
            }
        }

        System.out.println("Received: " + response.toString());

        // 关闭连接
        socketChannel.close();
    }
}